﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Reflection;
using Newtonsoft.Json;

namespace ZK.Common
{
    public class HttpClientUtil
    {
        /// <summary>
        /// 通过post方式请求接口
        /// </summary>
        /// <param name="url">请求全地址</param>
        /// <param name="isError">是否返回错误码</param>
        /// <returns>返回响应json字符串</returns>
        public static string doPostMethodToObj(string url, out bool isError)
        {
            string errorStr = string.Empty;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "post";
            request.KeepAlive = false;
            request.ContentType = "application/json;charset=UTF-8";
            request.Timeout = 10000;
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
                Common.Log4.LogManage.WriteInfo("请求接口地址为:" + url + ".返回数据为:" + response.ToString());
            }
            catch (Exception e)
            {
                isError = true;
                errorStr = getRestErrorMessage(response);
                Common.Log4.LogManage.WriteInfo("请求接口地址为:" + url + ".异常错误为:" + e.ToString());
                return errorStr;
            }
            isError = false;
            return getResponseString(response);
        }

        /// <summary>
        /// 通过post方式请求接口
        /// </summary>
        /// <param name="url">请求全地址</param>
        /// <param name="jsonBody">body输入</param>
        /// <param name="isError">是否返回错误码</param>
        /// <returns>返回响应json字符串</returns>
        public static string doPostMethodToObj(string url, string jsonBody, out bool isError)
        {
            string errorStr = string.Empty;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "post";
            request.KeepAlive = false;
            bool isToken = false;
            request.ContentType = "application/json;charset=UTF-8";
            request.Timeout = 10000;
            //for (int i = 0; i < TemporaryVar.notLoginTokenApiUrls.Length; i++)
            //{
            //    if (url.Contains(TemporaryVar.notLoginTokenApiUrls[i]))
            //    {
            //        isToken = true;
            //        request.Headers.Add("Authorization", TemporaryVar.fixedToken);
            //        break;
            //    }
            //}
            if (!string.IsNullOrEmpty(AppSession.UserInfo.Token) && !isToken)
            {
                request.Headers.Add("Authorization", AppSession.UserInfo.Token);
            }
            else
            {
                request.Headers.Add("Authorization", AppConfigHelper.GetAppSettings("Token"));
            }
            //request.Headers.Add("Authorization", AppSession.UserInfo.Token);
            if (!string.IsNullOrEmpty(jsonBody))
            {
                var stream = request.GetRequestStream();
                using (var writer = new StreamWriter(stream))
                {
                    writer.Write(jsonBody);
                    writer.Flush();
                }
            }
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
                Common.Log4.LogManage.WriteInfo("请求接口地址为:" + url + ".返回数据为:" + response.ToString());
            }
            //catch (WebException e)
            catch (Exception e)
            {
                //response = (HttpWebResponse)e.Response;
                isError = true;
                errorStr = getRestErrorMessage(response);
                Common.Log4.LogManage.WriteInfo("请求接口地址为:" + url + ".异常错误为:" + e.ToString());
                return errorStr;
            }
            isError = false;
            return getResponseString(response);
        }

        /// <summary>
        /// 通过get方式请求接口
        /// </summary>
        /// <param name="url">请求全地址</param>
        /// <param name="isError">是否返回错误码</param>
        /// <returns>返回响应json字符串</returns>
        public static string doGetMethodToObj(string url, out bool isError)
        {
            string errorStr = string.Empty;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.KeepAlive = false;
            request.ContentType = "application/json;charset=UTF-8;";
            request.Timeout = 10000;
            bool isToken = false;
            //for (int i = 0; i < TemporaryVar.notLoginTokenApiUrls.Length; i++)
            //{
            //    if (url.Contains(TemporaryVar.notLoginTokenApiUrls[i]))
            //    {
            //        isToken = true;
            //        request.Headers.Add("Authorization", TemporaryVar.fixedToken);
            //        break;
            //    }
            //}
            if (!string.IsNullOrEmpty(AppSession.UserInfo.Token) && !isToken)
            {
                request.Headers.Add("Authorization", AppSession.UserInfo.Token);
            }
            else
            {
                request.Headers.Add("Authorization", AppConfigHelper.GetAppSettings("Token"));
            }
           
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
                Common.Log4.LogManage.WriteInfo("请求接口地址为:" + url + ".返回数据为:" + response.ToString());
            }
            catch (Exception e)
            {
                isError = true;
                errorStr = getRestErrorMessage(response);
                Common.Log4.LogManage.WriteInfo("请求接口地址为:" + url + ".异常错误为:" + e.ToString());
                return errorStr;
            }
            isError = false;
            return getResponseString(response);
        }


        /// <summary>
        /// 通过put方式请求接口
        /// </summary>
        /// <param name="url">请求全地址</param>
        /// <param name="isError">是否返回错误码</param>
        /// <returns>返回响应json字符串</returns>
        public static string doPutMethod(string url, out bool isError)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "put";
            request.ContentType = "application/json;charset=UTF-8";
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException e)
            {
                response = (HttpWebResponse)e.Response;
                isError = true;
                return getRestErrorMessage(response);
            }
            isError = false;
            return getResponseString(response);
        }

        /// <summary>
        /// 通过put方式请求接口
        /// </summary>
        /// <param name="url">请求全地址</param>
        /// <param name="jsonBody">body输入</param>
        /// <param name="isError">是否返回错误码</param>
        /// <returns>返回响应json字符串</returns>
        public static string doPutMethodToObj(string url, string jsonBody, out bool isError)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "put";
            request.ContentType = "application/json;charset=UTF-8";
            var stream = request.GetRequestStream();
            using (var writer = new StreamWriter(stream))
            {
                writer.Write(jsonBody);
                writer.Flush();
            }
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException e)
            {
                response = (HttpWebResponse)e.Response;
                isError = true;
                return getRestErrorMessage(response);
            }
            isError = false;
            return getResponseString(response);

        }

        /// <summary>
        /// 通过delete方式请求接口
        /// </summary>
        /// <param name="url">请求全地址</param>
        /// <param name="isError">是否返回错误码</param>
        /// <returns>返回响应json字符串</returns>
        public static string doDeleteMethod(string url, out bool isError)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "DELETE";
            request.ContentType = "application/json;charset=UTF-8";
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException e)
            {
                response = (HttpWebResponse)e.Response;
                isError = true;
                return getRestErrorMessage(response);
            }
            isError = false;
            return getResponseString(response);
        }



        /// <summary>
        ///  将 HttpWebResponse 返回结果转换成 string
        /// </summary>
        /// <param name="response">HttpWebResponse对象</param>
        /// <returns>返回utf-8字符</returns>
        public static string getResponseString(HttpWebResponse response)
        {
            string json = null;
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8")))
            {
                try
                {
                    json = reader.ReadToEnd();
                }
                catch (Exception ex)
                {

                }
            }
            if (response != null)
            {
                response.Close();
            }
            return json;
        }

        // 获取异常信息
        private static string getRestErrorMessage(HttpWebResponse errorResponse)
        {
            string errorhtml = "";
            try
            {
                errorhtml = getResponseString(errorResponse);
            }
            catch (Exception ex)
            {

            }
            finally
            {
                if (errorResponse != null)
                {
                    errorResponse.Close();
                }
            }
            return errorhtml;
        }
        /// <summary>
        /// 将datas集合封装成json格式
        /// </summary>
        /// <param name="Datas">集合</param>
        /// <returns>json数据</returns>
        public static string GetJsonStr(Dictionary<string, string> Datas)
        {
            StringWriter sw = new StringWriter();
            JsonWriter writer = new JsonTextWriter(sw);

            writer.WriteStartObject();
            foreach (string item in Datas.Keys)
            {
                writer.WritePropertyName(item);
                writer.WriteValue(Datas[item]);
            }

            writer.WriteEndObject();
            writer.Flush();
            string jsonText = sw.GetStringBuilder().ToString();
            return jsonText;
        }
        /// <summary>
        /// list集合转换为datatable
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static DataTable toDataTable(IList list)
        {
            DataTable result = new DataTable();
            if (list.Count > 0)
            {
                FieldInfo[] fieldInfos = list[0].GetType().GetFields();
                foreach (FieldInfo fi in fieldInfos)
                {
                    result.Columns.Add(fi.Name, fi.FieldType);
                }

                for (int i = 0; i < list.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (FieldInfo fi in fieldInfos)
                    {
                        object obj = fi.GetValue(list[i]);
                        if (null == obj)
                        {
                            tempList.Add(obj);
                            continue;
                        }
                        object[] array = tempList.ToArray();
                        result.LoadDataRow(array, true);
                    }
                }

            }
            return result;

        }
    }
}
